package com.ruoyi.eqmonitor.service.impl;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.constant.UserConstants;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.eqmonitor.dispose.service.IotService;
import com.ruoyi.eqmonitor.domain.*;
import com.ruoyi.eqmonitor.dtos.OptDeviceDto;
import com.ruoyi.eqmonitor.exception.OpentsdbException;
import com.ruoyi.eqmonitor.exception.OpentsdbQueryException;
import com.ruoyi.eqmonitor.mapper.OptDeviceMonitorConfigMapper;
import com.ruoyi.eqmonitor.service.IOptDeviceAlarmService;
import com.ruoyi.eqmonitor.service.IOptDeviceMonitorConfigService;
import com.ruoyi.eqmonitor.utils.Constant;
import com.ruoyi.eqmonitor.utils.OpenTSDBUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.nio.reactor.IOReactorException;
import org.opentsdb.client.OpenTSDBClient;
import org.opentsdb.client.bean.request.SubQuery;
import org.opentsdb.client.bean.response.QueryResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;


/**
 * 设备监测预警配置Service业务层处理
 *
 * @author ruoyi
 * @date 2022-11-26
 */
@Slf4j
@Service
public class OptDeviceMonitorConfigServiceImpl extends ServiceImpl<OptDeviceMonitorConfigMapper, OptDeviceMonitorConfig> implements IOptDeviceMonitorConfigService {

    public static final String DEVICE_MONITOR_CONFIG_KEY = "device_monitor_config:";

    @Resource
    private OpenTSDBUtils openTSDBUtils;
    @Resource
    private RedisService redisService;
    @Resource
    private IOptDeviceAlarmService iOptDeviceAlarmService;
    @PostConstruct
    public void init() {
        Collection<String> keys = redisService.keys(DEVICE_MONITOR_CONFIG_KEY.concat("*"));
        if (CollectionUtil.isNotEmpty(keys)) {
            redisService.deleteObject(keys);
        }
        List<OptDeviceMonitorConfig> configs = list();
        Map<String, Map<String, List<OptDeviceMonitorConfig>>> group = configs.stream().collect(Collectors.groupingBy(OptDeviceMonitorConfig::getDeviceCode, Collectors.groupingBy(OptDeviceMonitorConfig::getAlarmCode)));
        for (Map.Entry<String, Map<String, List<OptDeviceMonitorConfig>>> entry : group.entrySet()) {
            if (StrUtil.isNotBlank(entry.getKey()) && MapUtil.isNotEmpty(entry.getValue())) {
                redisService.setCacheMap(getRedisHKey(entry.getKey()), entry.getValue());
            }
        }
        log.info("初始化设备阈值缓存完毕!");
    }

    @Override
    public OptDeviceMonitorConfig selectOptDeviceMonitorConfigById(Long id){
        return baseMapper.selectOptDeviceMonitorConfigById(id);
    }

    @Override
    public List<OptDeviceMonitorConfig> selectOptDeviceMonitorConfigList(OptDeviceMonitorConfig optDeviceMonitorConfig){
        return baseMapper.selectOptDeviceMonitorConfigList(optDeviceMonitorConfig);
    }

    /**
     * 根据设备 删除阈值配置
     * @param optDevices 设备实体列表
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int removeDeviceMonitorConfigByDevice(List<OptDevice> optDevices) {
        Set<String> deviceCodes = optDevices.stream().map(OptDevice::getDeviceCode).collect(Collectors.toSet());
        if (CollectionUtil.isNotEmpty(deviceCodes)) {
            int rows = baseMapper.delete(Wrappers.<OptDeviceMonitorConfig>lambdaQuery().in(OptDeviceMonitorConfig::getDeviceCode, deviceCodes));
            if (rows > 0) {
                for (String deviceCode : deviceCodes) {
                    redisService.deleteObject(getRedisHKey(deviceCode));
                }
            }
            return rows;
        }
        return 0;
    }

    /**
     * 更新阈值的设备编码
     * @param oldDeviceCode 原设备编码
     * @param newDeviceCode 新设备编码
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateDeviceCode(String oldDeviceCode, String newDeviceCode) {
        LambdaUpdateWrapper<OptDeviceMonitorConfig> updateWrapper = Wrappers.<OptDeviceMonitorConfig>lambdaUpdate()
                .eq(OptDeviceMonitorConfig::getDeviceCode, oldDeviceCode)
                .set(OptDeviceMonitorConfig::getDeviceCode, newDeviceCode);
        // 修改
        int rows = baseMapper.update(null, updateWrapper);
        if (rows > 0) {
            // 删除原有配置
            redisService.deleteObject(getRedisHKey(oldDeviceCode));
            // 刷新新的配置
            flushCacheByDeviceCode(newDeviceCode);
        }
        return rows;
    }



    /**
     * 切换状态
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int changeStatus(OptDeviceMonitorConfig config) {
        Assert.notBlank(config.getIsUse(), "是否使用不允许为空");
        Assert.notNull(config.getId(), "主键不允许为空");
        OptDeviceMonitorConfig info = getById(config.getId());
        if (ObjectUtil.isNull(info)) {
            throw new ServiceException("配置不存在");
        }
        int rows = baseMapper.update(null, Wrappers.<OptDeviceMonitorConfig>lambdaUpdate()
                .eq(OptDeviceMonitorConfig::getId, config.getId())
                .set(OptDeviceMonitorConfig::getIsUse, config.getIsUse())
        );
        if (rows > 0) {
            // 刷新新的配置
            flushCacheByDeviceCode(info.getDeviceCode());
        }
        return rows;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int saveDeviceMonitorConfig(OptDeviceMonitorConfig optDeviceMonitorConfig) {
        if (StrUtil.isBlank(optDeviceMonitorConfig.getDeviceCode())) {
            throw new ServiceException("设备编码不允许为空");
        }
        optDeviceMonitorConfig.setCreateTime(new Date());
        optDeviceMonitorConfig.setCreateBy(SecurityUtils.getUsername());
        int rows = baseMapper.insert(optDeviceMonitorConfig);
        if (rows > 0) {
            flushCacheByDeviceCode(optDeviceMonitorConfig.getDeviceCode());
        }
        return rows;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateDeviceMonitorConfigById(OptDeviceMonitorConfig config) {
        OptDeviceMonitorConfig oldInfo = getById(config.getId());
        if (ObjectUtil.isNull(oldInfo)) {
            throw new ServiceException("配置不存在");
        }
        if (StrUtil.isBlank(config.getDeviceCode())) {
            throw new ServiceException("设备编码不允许为空");
        }
        config.setUpdateTime(new Date());
        config.setUpdateBy(SecurityUtils.getUsername());
        int rows = baseMapper.updateById(config);
        if (rows > 0) {
            // 如果阈值发生变化，将报警表对应的记录 是否持续报警设置为false
            if (!ObjectUtil.equals(oldInfo.getAlarmValue(), config.getAlarmValue())
                    || !ObjectUtil.equals(oldInfo.getUpperLimit(), config.getUpperLimit())
                    || !ObjectUtil.equals(oldInfo.getFloorLimit(), config.getFloorLimit())) {
                iOptDeviceAlarmService.updatePersistentStatusToFalse(config.getDeviceCode(), config.getAlarmType(), config.getAlarmPhenomenon(), config.getAlarmCode());
            }
            flushCacheByDeviceCode(config.getDeviceCode());
        }
        return rows;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int removeDeviceMonitorConfigByIds(List<Long> ids) {
        List<OptDeviceMonitorConfig> optDeviceMonitorConfigs = listByIds(ids);
        // 删除数据
        int rows = baseMapper.deleteBatchIds(ids);
        // 删除缓存
        if (rows > 0 && CollectionUtil.isNotEmpty(optDeviceMonitorConfigs)) {
            Set<String> deviceCodeSet = optDeviceMonitorConfigs.stream()
                    .map(OptDeviceMonitorConfig::getDeviceCode).collect(Collectors.toSet());
            for (String deviceCode : deviceCodeSet) {
                flushCacheByDeviceCode(deviceCode);
            }
        }
        return rows;
    }

    /**
     * 根据设备编码刷新缓存
     * @param deviceCode 设备编码
     */
    private void flushCacheByDeviceCode(String deviceCode) {
        String redisHKey = getRedisHKey(deviceCode);
        redisService.deleteObject(redisHKey);
        List<OptDeviceMonitorConfig> configList = list(
                Wrappers.<OptDeviceMonitorConfig>lambdaQuery()
                        .eq(OptDeviceMonitorConfig::getDeviceCode, deviceCode)
        );
        if (CollectionUtil.isNotEmpty(configList)) {
            Map<String, List<OptDeviceMonitorConfig>> collect = configList.stream()
                    .collect(Collectors.groupingBy(OptDeviceMonitorConfig::getAlarmCode));
            redisService.setCacheMap(redisHKey, collect);
        }
    }

    /**
     * 获取阈值redis hkey
     * @param deviceCode 设备编码
     * @return redis hkey
     */
    @Override
    public String getRedisHKey(String deviceCode) {
        return DEVICE_MONITOR_CONFIG_KEY.concat(deviceCode);
    }

    @Override
    public void validateConfigAndDoAlarm(OptDeviceDto device, JSONArray messageArray) {
        if (device == null) {
            log.warn("解析阈值报警失败, 设备不存在");
            return;
        }
        String snCode = device.getDeviceCode();
        String deviceType = device.getDeviceType();
        Map<String, List<OptDeviceMonitorConfig>> monitorConfigMap = redisService.getCacheMap(getRedisHKey(snCode));
        /*try {
            //标记缓存是否刷新
            final boolean[] flag = {false};
            *//*
             * 判断是否满足 ((设备类型为一杆式河道监测站 且 监测类型为液位) 或 (设备类型为氨氮一体机 且 监测类型为流量))
             * 再判断阈值配置是否存在 且 对应监测类型的阈值配置是否存在
             *  不存在-->新增
             *  存在-->进一步判断（upDataMonitorConfig）
             *//*
            messageArray.parallelStream().forEach(item -> {
                JSONObject jsonObject = (JSONObject) item;
                String monitorCode = jsonObject.getStr("monitorCode");
                //((设备类型为一杆式河道监测站 且 监测类型为液位) 或 (设备类型为氨氮一体机 且 监测类型为流量))
                if ((Constant.EquipmentType.SE200_L_Y0.getCode().equals(deviceType) && Constant.MonitorInfo.M_0x05D1.getCode().equals(monitorCode))
                        || (Constant.EquipmentType.SR500_L_Y0_LDN.getCode().equals(deviceType) && Constant.MonitorInfo.M_0x0592.getCode().equals(monitorCode))) {
                    String monitorData = jsonObject.getStr("monitorData");
                    //阈值配置存在 且 对应监测类型的阈值配置存在
                    if (!MapUtil.isEmpty(monitorConfigMap) && monitorConfigMap.get(monitorCode).size() > 0){
                        flag[0] = this.upDataMonitorConfig(snCode,monitorCode,monitorConfigMap.get(monitorCode),monitorData);
                    }else {
                        flag[0] = this.saveMonitorConfig(snCode, monitorCode,monitorData);
                    }
                }
            });
            //刷新缓存，并重新解析
            if (flag[0]){
                flushCacheByDeviceCode(snCode);
                validateConfigAndDoAlarm(device,messageArray);
            }
        } catch (Exception e) {
            log.error("设置一杆式河道监测站液位或氨氮一体机流量阈值失败: {}，设备编码:{}", e.getMessage(),snCode);
            return;
        }*/

        if (MapUtil.isEmpty(monitorConfigMap)) {
            log.warn("设备: {} 阈值配置不存在", snCode);
            return;
        }

        // 防止传入的监测指标重复的太多 取最新的数据进行报警
        Map<String, Object> mapping = messageArray.parallelStream().collect(
                Collectors.toMap(
                        // 根据监测指标分组
                        (obj) -> {
                            JSONObject jsonObject = (JSONObject) obj;
                            // 如果不是监测指标 则获取参数指标字段
                            return jsonObject.getStr("monitorCode", jsonObject.getStr("attributeCode"));
                        },
                        // 取全部的数据
                        Function.identity(),
                        // 过滤最大的值
                        (c1, c2) -> {
                            JSONObject c1Obj = (JSONObject) c1;
                            JSONObject c2Obj = (JSONObject) c2;
                            Date c1Time = c1Obj.getDate("monitorTime", c1Obj.getDate("updateTime"));
                            Date c2Time = c2Obj.getDate("monitorTime", c2Obj.getDate("updateTime"));
                            return DateUtil.compare(c1Time, c2Time) > 0 ? c1 : c2;
                        }
                )
        );
        // 校验阈值
        mapping.values().forEach((obj) -> {
            JSONObject jsonObject = (JSONObject) obj;
            // 如果不是监测指标 则获取参数指标字段
            String monitorCode = jsonObject.getStr("monitorCode", jsonObject.getStr("attributeCode"));
            // 如果不是监测指标数据 则获取参数指标数据
            Double monitorData = jsonObject.getDouble("monitorData", jsonObject.getDouble("attributeData"));
            Date monitorTime = jsonObject.getDate("monitorTime", jsonObject.getDate("updateTime"));
            List<OptDeviceMonitorConfig> configList = monitorConfigMap.get(monitorCode);
            validateMonitor(configList, device, monitorData, monitorTime);
        });
    }

    @Override
    public void validateConfigAndDoAlarm(OptDeviceDto device, OptDeviceMonitorLastData monitorData) {
        if (device == null) {
            log.warn("解析阈值报警失败, 设备不存在");
            return;
        }
        List<OptDeviceMonitorConfig> configList = redisService.getCacheMapValue(getRedisHKey(device.getDeviceCode()), monitorData.getCode());
        if (CollectionUtil.isEmpty(configList)) {
            log.warn("设备: {} 阈值配置不存在", device.getDeviceCode());
            return;
        }
        validateMonitor(configList, device, monitorData.getCodeValue(), monitorData.getMonitorTime());
    }

    @Override
    public OptDeviceMonitorConfig getByDeviceCode(String deviceCode,String monitorCode) {
        return baseMapper.getByDeviceCode(deviceCode,monitorCode);
    }

    private void validateMonitor(List<OptDeviceMonitorConfig> optDeviceMonitorConfigList, OptDeviceDto device, Double monitorData, Date alarmTime) {
        if (monitorData != null && CollectionUtil.isNotEmpty(optDeviceMonitorConfigList)) {
            for (OptDeviceMonitorConfig config : optDeviceMonitorConfigList) {
                String isUse = config.getIsUse();
                Double alarmValue = config.getAlarmValue();
                Double upperLimit = config.getUpperLimit();
                Double floorLimit = config.getFloorLimit();
                // 含有监测指标 && 含有阈值配置 && 启用状态 && 监测数据合法 则进行报警判断
                if (UserConstants.NORMAL.equals(isUse)) {
                    OptDeviceAlarm optDeviceAlarm = iOptDeviceAlarmService.buildAlarmEntity(device, config, monitorData, alarmTime);
                    // 判断是阈值还是上下限
                    if (ObjectUtil.isNotNull(alarmValue) && NumberUtil.compare(alarmValue, monitorData) < 0) {
                        // 阈值 < 采集数据 则报警
                        // 超限告警 - 数据超限
                        iOptDeviceAlarmService.doSaveAlarm(optDeviceAlarm);
                    } else if (ObjectUtil.isNotNull(floorLimit) && NumberUtil.compare(monitorData, floorLimit) < 0) {
                        // 下限超限 采集数据 < 下限
                        // 上下限越界告警 - 下限越界告警
                        iOptDeviceAlarmService.doSaveAlarm(optDeviceAlarm);
                    } else if (ObjectUtil.isNotNull(upperLimit) && NumberUtil.compare(monitorData, upperLimit) > 0) {
                        // 上限超限 上限 < 采集数据
                        // 上下限越界告警 - 上限越界告警
                        iOptDeviceAlarmService.doSaveAlarm(optDeviceAlarm);
                    } else {
                        // 判断是否产生报警 如果产生报警 则修改是否持续报警字段为 否
                        iOptDeviceAlarmService.updatePersistentStatus(optDeviceAlarm);
                    }
                }
            }
        }
    }
    @Resource
    private IotService iotService;
    /**
     * 取上月液位均值
     * @param deviceCode 设备编码
     * @param monitorConfig 阈值配置
     * @param monitorData 监测数据
     */
    public OptDeviceMonitorConfig getBySnCodeLastMonth(String deviceCode,OptDeviceMonitorConfig monitorConfig,String monitorData) throws ParseException, OpentsdbException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String format = sdf.format(new Date());
        //获取上个月第一天
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(sdf.parse(format));
        calendar.add(Calendar.MONTH, -1);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        //获取上个月最后一天
        Calendar calendar1 = Calendar.getInstance();
        calendar1.setTime(sdf.parse(format));
        calendar1.set(Calendar.DAY_OF_MONTH, 1);
        calendar1.add(Calendar.DAY_OF_MONTH, -1);

        SubQuery.Filter snCodeFilter = OpenTSDBUtils.createSnCodeFilter(deviceCode);
        SubQuery.Filter monitorCodeFilter = OpenTSDBUtils.createMonitorCodeFilter(
                Constant.MonitorInfo.M_0x05D1.getCode());

        double avg = iotService.avgBySnAndCode(deviceCode,Constant.MonitorInfo.M_0x05D1.getCode(),calendar.getTime(),calendar1.getTime());
        if (avg > 0){
            BigDecimal divide = new BigDecimal(avg);
            monitorConfig.setFloorLimit(divide.multiply(new BigDecimal("0.8")).doubleValue());
            monitorConfig.setUpperLimit(divide.multiply(new BigDecimal("1.2")).doubleValue());
        }else {
            monitorConfig.setFloorLimit(new BigDecimal(monitorData).multiply(new BigDecimal("0.8")).doubleValue());
            monitorConfig.setUpperLimit(new BigDecimal(monitorData).multiply(new BigDecimal("1.2")).doubleValue());
        }
        return monitorConfig;
    }

    /**
     * 判断是否下雨（目前是固定取其中一台设备做判断依据，可以改为随机选取）
     */
    public boolean selectRainfall(String deviceCode) throws ParseException, OpentsdbException {
        //创建连接
        OpenTSDBClient queryClient = null;
        try {
            queryClient = openTSDBUtils.readClient();
        } catch (IOReactorException e) {
            log.error("创建opentsdb查询失败");
        }
        if (queryClient == null) {
            throw new OpentsdbException("查询opentsdb失败, queryClient不存在");
        }
        //起始时间为当天0点时间，结束时间为当前时间
        SimpleDateFormat dayFormat = new SimpleDateFormat("yyyyMMdd");
        Date date = new Date();
        Date beginTime = dayFormat.parse(dayFormat.format(date));
        //查询数据
        double sum = iotService.sumBySnAndCode(deviceCode,Constant.MonitorInfo.M_0x0566.getCode(),beginTime,date);
        //数据处理
        boolean flag = false;//标记是否降水
        if (sum > 0){
            flag = true;
        }
        return flag;
    }

    /**
     * 新增阈值配置（仅设备类型为一杆式河道监测站 且 监测类型为液位
     *              设备类型为氨氮一体机 且 监测类型为流量）
     * @param snCode 设备编码
     * @param monitorCode 监测类型编码
     * @param monitorData 监测数据
     */
    public boolean saveMonitorConfig(String snCode,String monitorCode,String monitorData){
        if (Constant.MonitorInfo.M_0x05D1.getCode().equals(monitorCode)){
            //设备类型为一杆式河道监测站 且 监测类型为液位
            OptDeviceMonitorConfig disposeData = null;
            try {
                disposeData = getBySnCodeLastMonth(snCode, new OptDeviceMonitorConfig(),monitorData);
            } catch (OpentsdbException | ParseException e) {
                log.error("查询一杆式河道监测站液位高度失败",e);
            }
            if (disposeData != null) {
                disposeData.setDeviceCode(snCode);
                disposeData.setAlarmCode(Constant.MonitorInfo.M_0x05D1.getCode());
                disposeData.setAlarmPhenomenon("11");
                disposeData.setAlarmType("1");
                int i = saveDeviceMonitorConfig(disposeData);
                return i > 0;
            }
        }else {
            //设备类型为氨氮一体机 且 监测类型为流量
            // 如果下雨，不发生报警
            // 如果晴天，流量不为0，则发生报警
            boolean b = false;
            try {
                b = selectRainfall(snCode);
            } catch (ParseException | OpentsdbException e) {
                log.error("查询氨氮一体机流量失败",e);
            }
            OptDeviceMonitorConfig monitorConfig = new OptDeviceMonitorConfig();
            monitorConfig.setDeviceCode(snCode);
            monitorConfig.setAlarmCode(Constant.MonitorInfo.M_0x0592.getCode());
            monitorConfig.setAlarmPhenomenon("12");
            monitorConfig.setAlarmType("0");
            //下雨则999.999，否则0.001
            monitorConfig.setAlarmValue(b ? 999.999 : 0.001);
            monitorConfig.setFloorLimit(null);
            monitorConfig.setUpperLimit(null);
            int i = saveDeviceMonitorConfig(monitorConfig);
            return i > 0;
        }
        return false;
    }

    /**
     * 过滤相关参数是否存在
     *        不存在-->新增
     *        存在-->判断阈值是否为当月(一杆式河道监测站) 或 当天(氨氮一体机)
     *              否-->更新
     * @param snCode 设备编码
     * @param monitorCode 监测数据编码
     * @param monitorConfigs 设备阈值配置
     * @param monitorData 监测数据
     */
    public boolean upDataMonitorConfig(String snCode,String monitorCode,List<OptDeviceMonitorConfig> monitorConfigs,String monitorData){
        //一杆式河道监测站
        if (Constant.MonitorInfo.M_0x05D1.getCode().equals(monitorCode)){
            List<OptDeviceMonitorConfig> configStream = monitorConfigs.stream()
                    .filter(m -> m.getAlarmType().equals("1") && m.getAlarmPhenomenon().equals("11")).collect(Collectors.toList());
            if (configStream.size() > 0){
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
                for (OptDeviceMonitorConfig monitorConfig : configStream){
                    String format = sdf.format(new Date()); //本月时间格式化
                    Date updateTime = monitorConfig.getUpdateTime();
                    if (updateTime == null){
                        updateTime = monitorConfig.getCreateTime();
                    }
                    String format1 = sdf.format(updateTime);//更新时间格式化
                    if (!format.equals(format1)) {
                        OptDeviceMonitorConfig disposeData = null;
                        try {
                            disposeData = getBySnCodeLastMonth(snCode, monitorConfig,monitorData);
                        } catch (ParseException | OpentsdbException e) {
                            log.error("查询一杆式河道监测站液位高度失败",e);
                        }
                        //更新设备监测预警配置
                        if (disposeData != null) {
                            int i = updateDeviceMonitorConfigById(disposeData);
                            return i > 0;
                        }
                    }
                }
            }else {
                return this.saveMonitorConfig(snCode, monitorCode,monitorData);
            }
        }else {
            //氨氮一体机
            List<OptDeviceMonitorConfig> configStream = monitorConfigs.stream()
                    .filter(m -> m.getAlarmType().equals("0") && m.getAlarmPhenomenon().equals("12")).collect(Collectors.toList());
            if (configStream.size() > 0){
                boolean b = false;
                try {
                    b = selectRainfall(snCode);
                } catch (ParseException | OpentsdbException e) {
                    log.error("查询是否下雨失败",e);
                }
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                for (OptDeviceMonitorConfig monitorConfig : configStream){
                    String format = sdf.format(new Date()); //本日时间格式化
                    Date updateTime = monitorConfig.getUpdateTime();
                    if (updateTime == null){
                        updateTime = monitorConfig.getCreateTime();
                    }
                    String format1 = sdf.format(updateTime);//更新时间格式化并判断
                    if (!format.equals(format1)) {
                        //下雨则999.999，否则0.001
                        monitorConfig.setAlarmValue(b ? 999.999 : 0.001);
                        monitorConfig.setFloorLimit(null);
                        monitorConfig.setUpperLimit(null);
                        int i = updateDeviceMonitorConfigById(monitorConfig);
                        return i > 0;
                    }
                }
            }else {
                return this.saveMonitorConfig(snCode, monitorCode,monitorData);
            }
        }
        return false;
    }

}
